package com.ruoyi.video.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.video.domain.OnvifCamera;
import com.ruoyi.video.domain.VideoCamera;
import com.ruoyi.video.server.onvif.DiscoveryDeviceImpl;
import com.ruoyi.video.server.onvif.lib.BroadcastDiscovery;
import com.ruoyi.video.server.onvif.OnvifServer;
import com.ruoyi.video.service.IVideoCameraService;
import com.ruoyi.video.service.IVideoConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 摄像机Controller
 * 
 * @author ruoyi
 * @date 2024-12-09
 */
@RestController
@RequestMapping("/video/onvif")
public class VideoOnvifController extends BaseController
{
    @Autowired
    private IVideoCameraService videoCameraService;
    @Autowired
    private IVideoConfigService videoConfigService;
    @Autowired
    private OnvifServer onvifServer;

    /**
     * 查询摄像机列表
     */
    @GetMapping("/list")
    public AjaxResult list()
    {
        List<OnvifCamera> list = DiscoveryDeviceImpl.cameraMap.values().stream().filter(e->{return e.getCameraId().intValue() == -1;}).collect(Collectors.toList());
        return success(list);
    }


    /**
     * 开始搜索
     */
    @GetMapping("/start")
    public AjaxResult start(@RequestParam("username") String username, @RequestParam("password") String password)
    {
        onvifServer.tryLogin(username, password);
        return success();
    }

    /**
     * 停止搜索
     */
    @GetMapping("/stop")
    public AjaxResult stop()
    {
        BroadcastDiscovery.stop();
        DiscoveryDeviceImpl.cameraMap.clear();
        return success();
    }

    /**
     * 添加ONVIF设备
     * @return
     */
    @PreAuthorize("@ss.hasPermi('video:camera:add')")
    @Log(title = "摄像机", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody String[] ips){
        Map<String, String> config = videoConfigService.selectVideoServerConfig(onvifServer.getCode());
        if(!config.containsKey("username") || StringUtils.isEmpty(config.get("username"))){
            return AjaxResult.error("ONVIF登录账号不能为空");
        }
        if(!config.containsKey("password") || StringUtils.isEmpty(config.get("password"))){
            return AjaxResult.error("ONVIF登录密码不能为空");
        }

        int ret = 0;
        for(String ip:ips) {
            OnvifCamera onvifCamera = DiscoveryDeviceImpl.cameraMap.get(ip);
            if(StringUtils.isEmpty(onvifCamera.getToken())){
                continue;
            }
            if(StringUtils.isEmpty(onvifCamera.getRtsp())){
                continue;
            }
            VideoCamera vcc = new VideoCamera();
            vcc.setType(onvifServer.getCode());
            vcc.setIp(ip);
            VideoCamera videoCamera = videoCameraService.selectVideoCameraByIp(onvifServer.getCode(), ip);
            if(videoCamera == null) {
                videoCamera = new VideoCamera();
                videoCamera.setIp(ip);
                videoCamera.setType(vcc.getType());
                videoCamera.setChannels(1);
                if(StringUtils.isEmpty(onvifCamera.getName())){
                    videoCamera.setName("ONVIF "+onvifCamera.getIp());
                }else {
                    videoCamera.setName(onvifCamera.getName());
                }
                videoCamera.setCode(onvifCamera.getDeviceId());
                videoCamera.setPort(onvifCamera.getPort());
                videoCamera.setGroupId(1L);
                videoCamera.setOnline("Y");
                videoCamera.setUsername(onvifCamera.getUsername());
                videoCamera.setPassword(onvifCamera.getPassword());
                videoCamera.setStatus("1");
                videoCamera.setRtsp(onvifCamera.getRtsp());
                videoCamera.setCreateBy(getUsername());
                videoCameraService.insertVideoCamera(videoCamera);
            }
            onvifCamera.setCameraId(videoCamera.getId());
            ret ++;
        }
        return AjaxResult.success("成功添加 "+ret+" 个ONVIF摄像机");
    }
}
